package com.sk.orm.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.persistence.AttributeConverter;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author smy
 * {@code @date} 2022/11/6
 */
public class BaseDBConvertJsonList<T> implements AttributeConverter<List<T>, String> {
    private final Class<T> c;

    public BaseDBConvertJsonList(Class<T> c) {
        this.c = c;
    }

    @Override
    public final String convertToDatabaseColumn(List<T> attribute) {
        return CollectionUtils.isEmpty(attribute) ? null : JSONObject.toJSONString(attribute);
    }

    @Override
    public final List<T> convertToEntityAttribute(String dbData) {
        return dbData == null ? new ArrayList<>() : JSONArray.parseArray(dbData, c);
    }
}
